package com.antdesignbackend.backend.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.MD5;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.config.WxPayAppConfig;
import com.antdesignbackend.backend.entity.*;
import com.antdesignbackend.backend.entity.entityVo.*;
import com.antdesignbackend.backend.mapper.AppointmentMapper;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.mysql.cj.xdevapi.JsonArray;
import org.apache.catalina.User;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.mapping.ResultMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 公众号接口
 */
@Controller
@RequestMapping("/Interface")
public class InterfaceController {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IRoomService roomService;
    @Autowired
    private IShopService shopService;
    @Autowired
    IAppointmentService appointmentService;
    @Autowired
    AppointmentMapper appointmentMapper;
    @Autowired
    UserService userService;
    @Autowired
    private IImagesService imagesService;
    @Autowired
    private WxPayAppConfig wxPayAppConfig;
    @Autowired
    CabinetitemService cabinetitemService;
    @Autowired
    CabinetService cabinetService;
    @Autowired
    ActionService actionService;
    @Autowired
    CouponService couponService;
    @Autowired
    MiddlecommandService middlecommandService;
    @Autowired
    RegistorderService registorderService;
    @Autowired
    EventService eventService;
    @Autowired
    EventplannService eventplannService;
    @Autowired
    private UserRolesService userRolesService;

    /**
     *  营业时间段
     * @param roomId 房间id
     * @param date 日期
     * @return
     */
    @GetMapping("/getTimeInfo")
    @ResponseBody
    public Map getTimeInfo(@RequestParam(value = "roomId",required = false) Integer roomId,
                           @RequestParam(value = "date",required = false) String date,
                           @RequestParam(value = "isRenew",required = false) Integer isRenew) throws ParseException {
        LinkedHashMap map=new LinkedHashMap();
        SimpleDateFormat diff = new SimpleDateFormat("HH:mm");
        SimpleDateFormat nextdf = new SimpleDateFormat("yyyy-MM-dd");
        Date nextTime = new Date();Boolean nextFlag=true;Date dateStrm=null;String dealStartime=null;
        if(isRenew!=null&&isRenew==1){
            //续费
            QueryWrapper<Appointment> timeWrapper =new QueryWrapper<Appointment>();
            timeWrapper.gt("endTime",new Date());
            timeWrapper.eq("state",1);
            timeWrapper.eq("roomId",roomId);
            List<Appointment> timeOrder=appointmentService.list(timeWrapper);
            if(timeOrder.size()>0){
                Room entity =roomService.getById(roomId);
                Shop shop=shopService.getById(entity.getShopId());
                String startTime=diff.format(timeOrder.get(0).getEndTime());
                String endTime=shop.getEndTime();
                //获取已经预约时间段
                List<String> list=new ArrayList<>();
                QueryWrapper<Appointment> wrapper =new QueryWrapper<Appointment>();
                wrapper.eq("roomId",roomId);
                wrapper.eq("appointDate",date);
                wrapper.ne("state",-1);
                List<Appointment> datalist= appointmentService.getBaseMapper().selectList(wrapper);
                for(Appointment appoint:datalist){
                    String sarr[]=diff.format(appoint.getStartTime()).split(" ");
                    String start=sarr[0];
                    String earr[]=diff.format(appoint.getEndTime()).split(" ");
                    String end=earr[0];
                    List<String> dealTime=dealTime(start,end);
                    list.addAll(dealTime);
                }
                List<String> listdeal=new ArrayList<>();
                List<String> listdeal2=new ArrayList<>();
                for(Appointment appointment:timeOrder){
                    String time=diff.format(appointment.getEndTime());
                    listdeal.add(time);
                    String time2=diff.format(appointment.getStartTime());
                    listdeal2.add(time2);
                }
                if(startTime.compareTo(endTime)<0){
                    //设立预约标识
                    map.put(startTime,0);
                    String addTime="";
                    Calendar calendars = Calendar.getInstance();
                    calendars.setTime(diff.parse(startTime));
                    for(;!addTime.equals(endTime);){
                        calendars.add(Calendar.MINUTE, +30);
                        addTime=diff.format(calendars.getTime());
                        String flag="0";
                        for(String s:list){
                            if(s.equals(addTime)){
                                flag="1";
                            }
                        }
                        map.put(addTime,Integer.valueOf(flag));
                        if(addTime.equals("23:30") && endTime.equals("24:00")){
                            for(String s:list){
                                if(s.equals("24:00")){
                                    flag="1";
                                }
                            }
                            map.put("24:00",Integer.valueOf(flag));
                            break;
                        }
                    }
                    //标记为0
                    for(String s:listdeal){
                        if(map.get(s)!=null && !map.get(s).equals("")){
                            map.put(s,0);
                        }
                    }
                    for(String s:listdeal2){
                        if(map.get(s)!=null && !map.get(s).equals("")){
                            map.put(s,1);
                        }
                    }
                }
            }
        }else {
            if(nextdf.format(nextTime).equals(date)){
                //去除当前时间以前的时间
                long currentTime = System.currentTimeMillis();
                Date dateTime = new Date(currentTime);
                String nowTime= diff.format(dateTime);
                String strmNow = nowTime.substring(0,nowTime.length()-2)+"00";
                /*dateStrm=diff.parse(strmNow);
                dateStrm.setTime(dateStrm.getTime() + 60*60*1000);
                dealStartime=diff.format(dateStrm);*/
                dateStrm=diff.parse(strmNow);
                dealStartime=strmNow;
                nextFlag=false;
            }
            try {
                Room entity =roomService.getById(roomId);
                Shop shop=shopService.getById(entity.getShopId());
                List<String> list=new ArrayList<>();
                QueryWrapper<Appointment> wrapper =new QueryWrapper<Appointment>();
                wrapper.eq("roomId",roomId);
                wrapper.eq("appointDate",date);
                wrapper.ne("state",-1);
                List<Appointment> datalist= appointmentService.getBaseMapper().selectList(wrapper);
                for(Appointment appoint:datalist){
                    String sarr[]=diff.format(appoint.getStartTime()).split(" ");
                    String start=sarr[0];
                    String earr[]=diff.format(appoint.getEndTime()).split(" ");
                    String end=earr[0];
                    List<String> dealTime=dealTime(start,end);
                    list.addAll(dealTime);
                }
                //获取营业时间段
                Date lateTime = new Date();
                String startTime=shop.getStartTime();
                String endTime=shop.getEndTime();
                if(!nextFlag){
                    if(dateStrm.compareTo(diff.parse(startTime))>0){
                        startTime=dealStartime;
                    }
                    if(diff.format(lateTime).compareTo(endTime)>0 || startTime.compareTo(endTime)>=0){
                        return null;
                    }
                }
                String state="0";
                for(String s:list){
                    if(s.equals(startTime)){
                        state="1";
                    }
                }
                map.put(startTime,Integer.valueOf(state));
                String addTime="";
                SimpleDateFormat df = new SimpleDateFormat("HH:mm");
                Calendar calendars = Calendar.getInstance();
                calendars.setTime(df.parse(startTime));
                for(;!addTime.equals(endTime);){
                    calendars.add(Calendar.MINUTE, +30);
                    addTime=df.format(calendars.getTime());
                    String flag="0";
                    for(String s:list){
                        if(s.equals(addTime)){
                            flag="1";
                        }
                    }
                    map.put(addTime,Integer.valueOf(flag));
                    if(addTime.equals("23:30") && endTime.equals("24:00")){
                        for(String s:list){
                            if(s.equals("24:00")){
                                flag="1";
                            }
                        }
                        map.put("24:00",Integer.valueOf(flag));
                        break;
                    }
                }
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
        return map;
    }
    public List<String> dealTime(String start,String end) throws ParseException {
        String addTime="";
        List<String> list=new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        Calendar calendars = Calendar.getInstance();
        calendars.setTime(df.parse(start));
        list.add(start);
        for(;!addTime.equals(end);){
            calendars.add(Calendar.MINUTE, +30);
            addTime=df.format(calendars.getTime());
            list.add(addTime);
        }
        return list;
    }
    /**
     *  是否可预约
     * @param roomId 房间id
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @GetMapping("/isAppoint")
    @ResponseBody
    public Boolean IsAppoint(@RequestParam(value = "roomId",required = false) Integer roomId,
                             @RequestParam(value = "startTime",required = false) String startTime,
                             @RequestParam(value = "endTime",required = false) String endTime) {
        Boolean b=false;
        try
        {
            QueryWrapper<Appointment> queryWrapper = new QueryWrapper<>();
            queryWrapper.ne("state",-1);
            queryWrapper.eq("roomId",roomId);
            queryWrapper.and(wra -> wra.le("startTime", startTime).ge("endTime", startTime).or().ge("endTime", endTime).le("startTime", endTime).or().ge("startTime", startTime).le("endTime", endTime));
            List<Appointment> datalist=appointmentMapper.selectList(queryWrapper);
            if(datalist.size()==0)
            {
                b=true;
            }
        }
        catch(Exception ex) {
            log.error(ex.getMessage());
        }
        return b;
    }
    /**
     *  是否可续费
     * @param roomId 房间id
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @GetMapping("/isRenewal")
    @ResponseBody
    public Boolean isRenewal(@RequestParam(value = "roomId",required = false) Integer roomId,
                             @RequestParam(value = "startTime",required = false) String startTime,
                             @RequestParam(value = "endTime",required = false) String endTime) {
        Boolean b=false;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            QueryWrapper<Appointment> queryWrapper = new QueryWrapper<>();
            queryWrapper.ne("state",-1);
            queryWrapper.eq("roomId",roomId);
            queryWrapper.ge("startTime",startTime);
            List<Appointment> datalist=appointmentMapper.selectList(queryWrapper.orderByAsc("startTime"));
            if(datalist.size()==0){
                b=true;
            }else {
                if(datalist.get(0).getStartTime().compareTo(df.parse(endTime))>0){
                    b=true;
                }
            }
        }
        catch(Exception ex) {
            log.error(ex.getMessage());
        }
        return b;
    }

    /**
     *  订单列表
     * @param openId 小程序id
     * @return
     */
    @GetMapping("/getOrderInfo")
    @ResponseBody
    public List<AppletAppoint> getOrderInfo(@RequestParam(value = "openId",required = false) String openId,HttpServletRequest request){
        List<AppletAppoint> listTotal = new ArrayList<>();
        Map map=new HashMap();
        if(openId==null || openId.equals("")){
            if (request.getSession().getAttribute("openid") != null){
                openId=request.getSession().getAttribute("openid").toString();
            }
        }
        if(openId==null || openId.equals("")){
            return null;
        }
        try {
            List<AppointmentVo> appointList = new ArrayList<>();
            QueryWrapper<AppointmentVo> wrapper = new QueryWrapper<>();
            wrapper.eq("u.openId",openId);
            //wrapper.eq("t.isUse",0);
            wrapper.eq("t.state",0);
            appointList= appointmentService.searchs(wrapper);
            List<AppointmentVo> unUsedList = new ArrayList<>();
            List<AppointmentVo> useList = new ArrayList<>();
            List<AppointmentVo> cancelList = new ArrayList<>();
            QueryWrapper<AppointmentVo> unUsedWrapper = new QueryWrapper<>();
            unUsedWrapper.eq("u.openId",openId);
            unUsedWrapper.eq("t.isUse",0);
            unUsedWrapper.eq("t.state",1);
            unUsedList= appointmentService.searchs(unUsedWrapper);
            QueryWrapper<AppointmentVo> useWrapper = new QueryWrapper<>();
            useWrapper.eq("u.openId",openId);
            useWrapper.eq("t.isUse",1);
            useWrapper.eq("t.state",1);
            useList= appointmentService.searchs(useWrapper);
            QueryWrapper<AppointmentVo> cancelWrapper = new QueryWrapper<>();
            cancelWrapper.eq("u.openId",openId);
            cancelWrapper.eq("t.isUse",0);
            cancelWrapper.eq("t.state",1);
            cancelWrapper.eq("t.IsCancel",1);
            cancelList= appointmentService.searchs(cancelWrapper);
            listTotal.addAll(getAppletAppoint(appointList,0));
            listTotal.addAll(getAppletAppoint(unUsedList,1));
            listTotal.addAll(getAppletAppoint(useList,2));
            listTotal.addAll(getAppletAppoint(cancelList,3));
            Collections.sort(listTotal, new Comparator<AppletAppoint>() {
                @Override
                public int compare(AppletAppoint o1, AppletAppoint o2) {
                    //降序
                    return o2.getCreateTime().compareTo(o1.getCreateTime());
                }
            });
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return listTotal;
    }
    /**
     *  续费订单
     * @return
     */
    @GetMapping("/renewalOrder")
    @ResponseBody
    public List<AppletAppoint> renewalOrder(@RequestParam(value = "openId",required = false) String openId) {
        QueryWrapper<Users> queryWrapper =new QueryWrapper<Users>();
        queryWrapper.eq("openId",openId);
        Users users=userService.getOne(queryWrapper);
        QueryWrapper<AppointmentVo> wrapper =new QueryWrapper<AppointmentVo>();
        wrapper.eq("t.state",1);
        wrapper.ne("t.isCancel",1);
        wrapper.eq("t.userId",users.getUserID());
        wrapper.gt("t.endTime",new Date());
        List<AppointmentVo> order=appointmentService.searchs(wrapper);
        List<AppletAppoint> dealList=new ArrayList<>();
        for(AppointmentVo appointmentVo:order){
            Date start=appointmentVo.getEndTime();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendare = Calendar.getInstance();
            calendare.setTime(start);
            calendare.add(Calendar.MINUTE, +90);
            Date end=calendare.getTime();
            QueryWrapper<Appointment> timeWrapper =new QueryWrapper<Appointment>();
            timeWrapper.ge("startTime",start);
            timeWrapper.le("startTime",end);
            timeWrapper.ne("state",-1);
            List<Appointment> timeOrder=appointmentService.list(timeWrapper);
            if(timeOrder.size()>0){
                List<AppointmentVo> orderlist=new ArrayList<>();
                orderlist.add(appointmentVo);
                List<AppletAppoint> list= getAppletAppoint(orderlist,6);
                dealList.addAll(list);
            }else {
                List<AppointmentVo> orderlist=new ArrayList<>();
                orderlist.add(appointmentVo);
                List<AppletAppoint> list= getAppletAppoint(orderlist,5);
                dealList.addAll(list);
            }
        }
        return dealList;
    }
    public List<AppletAppoint> getAppletAppoint(List<AppointmentVo> list,Integer status){
        List<AppletAppoint> appletAppoint = list.stream().map(appoint -> {
            AppletAppoint applet = new AppletAppoint();
            BeanUtils.copyProperties(appoint, applet);
            applet.setId(appoint.getId());
            applet.setOrderNumber(appoint.getOrderNumber());
            applet.setStartTime(appoint.getStartTime());
            applet.setEndTime(appoint.getEndTime());
            applet.setCreateTime(appoint.getCreateTime());
            applet.setShopName(appoint.getShopName());
            applet.setRoomName(appoint.getRoomName());
            applet.setAmount(appoint.getAmount());
            applet.setImageUrl(getImage(appoint.getRoomId()));
            applet.setStatus(status);
            applet.setPaymentTime(appoint.getPaymentTime());
            applet.setShopId(appoint.getShopId());
            applet.setRoomId(appoint.getRoomId());
            return applet;
        }).collect(Collectors.toList());
        return appletAppoint;
    }
    public String getImage(Integer roomId){
        String imageUrl="";
        QueryWrapper<Images> wrapper=new QueryWrapper<Images>();
        wrapper.eq("type",2);
        wrapper.eq("pid",roomId);
        List<Images> datalist=imagesService.list(wrapper);
        if(datalist.size()>0){
            imageUrl= WebConfig.host+"images/"+datalist.get(0).getUrl();
        }
        return imageUrl;
    }
    /***
     * 根据id退款
     */
    @GetMapping("/cancelById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        ReturnVO result = new ReturnVO();
        Integer orderNo=Integer.parseInt(id.toString());
        JSONObject object= refund(orderNo);
        if (object.get("errMsg").equals("退款申请成功")) {
            result.setMessage("退款成功");
            result.setCode("200");
        }else {
            result.setMessage("退款失败");
            result.setCode("500");
        }
        return result;
    }
    //小程序退款
    public JSONObject refund(Integer id){
        JSONObject object=new JSONObject();
        //获取订单
        Appointment appointment=appointmentService.getById(id);
        Integer payState = appointment.getState();
        Integer isUse = appointment.getIsUse();
        Integer isCancel = appointment.getIsCancel();
        Double amount=appointment.getAmount();
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String checkInTime = formatter.format(appointment.getStartTime());
        //判断订单是否可以退款
        if (payState != 1 && isUse != 0 && isCancel != 1) {
            object.put("errMsg","该订单无法申请退款");
            return object;
        }
        Date date = new Date();
        String today = formatter.format(date);
        int compareTo = today.compareTo(checkInTime);
        if (compareTo >= 0) {
            object.put("errMsg","该订单无法申请退款");
            return object;
        }
        if(amount <= 0){
            object.put("errMsg","退款金额必须大于0");
            return object;
        }
        //退款开始
        Map<String, String> responseMap = new HashMap<>();
        Map<String, String> resultData= new HashMap<>();
        try {
            DecimalFormat df = new DecimalFormat("######0");
            String total_fee = String.valueOf(df.format((amount * 100)));
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("appid", wxPayAppConfig.getAppID());
            map.put("mch_id", wxPayAppConfig.getMchID());
            map.put("nonce_str", String.valueOf(id));
            map.put("out_trade_no", String.valueOf(id));
            map.put("out_refund_no", String.valueOf(id));
            map.put("total_fee", total_fee);
            map.put("refund_fee", total_fee);
            map.put("op_user_id", wxPayAppConfig.getMchID());
            map.put("refund_fee_type", "CNY");
            String paySign = getPayCustomSign(map, wxPayAppConfig.getKey());
            map.put("sign", paySign);
            String xml = ArrayToXml(map);
            String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            String post = post(url, xml);
            resultData = doXMLParse(post);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String return_code = resultData.get("return_code");   //返回状态码
        String return_msg = resultData.get("return_msg");     //返回信息
        if ("SUCCESS".equals(return_code)) {
            String result_code = resultData.get("result_code");       //业务结果
            String err_code_des = resultData.get("err_code_des");     //错误代码描述
            if ("SUCCESS".equals(result_code)) {
                //修改用户订单状态为已退款
                appointment.setIsCancel(0);
                object.put("errMsg","退款申请成功");
                return object;
            } else {
                log.info("订单号:{}错误信息:{}", id, err_code_des);
                object.put("errMsg",err_code_des);
                return object;
            }
        } else {
            log.info("订单号:{}错误信息:{}", id, return_msg);
            object.put("errMsg",return_msg);
            return object;
        }
    }
    public static String getPayCustomSign(HashMap<String, String> bizObj, String key) throws Exception {
        String bizString = FormatBizQueryParaMap(bizObj, false);
        return sign(bizString, key);
    }
    public static String FormatBizQueryParaMap(HashMap<String, String> paraMap, boolean urlencode) throws Exception {
        String buff = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(paraMap.entrySet());
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            for (int i = 0; i < infoIds.size(); i++) {
                Map.Entry<String, String> item = infoIds.get(i);
                if (item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (urlencode) {
                        val = URLEncoder.encode(val, "utf-8");
                    }
                    buff += key + "=" + val + "&";
                }
            }
            if (buff.isEmpty() == false) {
                buff = buff.substring(0, buff.length() - 1);
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return buff;
    }
    public static String sign(String content, String key) throws Exception {
        String signStr = "";
        signStr = content + "&key=" + key;
        return MD5.encrypt(signStr);
    }
    public static String ArrayToXml(Map<String, String> arr) {
        String xml = "<xml>";
        Iterator<Map.Entry<String, String>> iter = arr.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, String> entry = iter.next();
            String key = entry.getKey();
            String val = entry.getValue();
            if (IsNumeric(val)) {
                xml += "<" + key + ">" + val + "</" + key + ">";
            } else
                xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";
        }
        xml += "</xml>";
        return xml;
    }
    public static boolean IsNumeric(String str) {
        if (str.matches("\\d *")) {
            return true;
        } else {
            return false;
        }
    }
    private static String post(String url, String xmlParam) {
        StringBuilder sb = new StringBuilder();
        try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream instream = new FileInputStream(new File("cert/apiclient_cert.p12"));
            try {
                keyStore.load(instream, "商户号".toCharArray());
            } finally {
                instream.close();
            }
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "商户号".toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                    null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            HttpPost httpPost = new HttpPost(url);
            StringEntity reqEntity = new StringEntity(xmlParam);
            reqEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(reqEntity);
            CloseableHttpResponse response = client.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(entity.getContent(), "UTF-8"));
                    String text = "";
                    while ((text = bufferedReader.readLine()) != null) {
                        sb.append(text);
                    }
                }
                EntityUtils.consume(entity);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    private static Map<String, String> doXMLParse(String xml) throws XmlPullParserException, IOException {
        InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
        Map<String, String> map = null;
        XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
        pullParser.setInput(inputStream, "UTF-8");
        int eventType = pullParser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    map = new HashMap<String, String>();
                    break;
                case XmlPullParser.START_TAG:
                    String key = pullParser.getName();
                    if (key.equals("xml"))
                        break;
                    String value = pullParser.nextText();
                    map.put(key, value);
                    break;
                case XmlPullParser.END_TAG:
                    break;
            }
            eventType = pullParser.next();
        }
        return map;
    }

    //产生订单号
    public String paymentID(){
        int r1=(int)(Math.random()*(10));//产生2个0-9的随机数
        int r2=(int)(Math.random()*(10));
        long now = System.currentTimeMillis();//一个13位的时间戳
        String paymentID0 =String.valueOf(r1)+String.valueOf(r2)+String.valueOf(now);
        int r3=(int)(Math.random()*(10));//产生2个0-9的随机数
        int r4=(int)(Math.random()*(10));
        String paymentID = paymentID0 +String.valueOf(r3)+String.valueOf(r4);// 订单ID
        return paymentID;
    }

    /**
     *  判断是否拥有包月权益
     * @param userId 用户id
     * @return
     */
    @GetMapping("/isMonthly")
    @ResponseBody
    public boolean isMonthly(@RequestParam(value = "userId",required = false) Integer userId){
        Boolean b=false;
        Users users=userService.getById(userId);
        if(users.getIsMonthly()==1){
            b=true;
        }
        return b;
    }
    /**
     *  包月权益用户预约
     * @param roomId 房间id
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @GetMapping("/monthlyAppoint")
    @ResponseBody
    public Boolean monthlyAppoint(@RequestParam(value = "shopId",required = false) Integer shopId,
                                  @RequestParam(value = "roomId",required = false) Integer roomId,
                                  @RequestParam(value = "startTime",required = false) String startTime,
                                  @RequestParam(value = "endTime",required = false) String endTime,
                                  @RequestParam(value = "amount",required = false) Double amount,
                                  @RequestParam(value = "userId",required = false) Integer userId) {
        Boolean b=false;
        try
        {
            Users users=userService.getById(userId);
            Shop shop=shopService.getById(shopId);
            if(users.getIsMonthly()==1 && shop.getTypeofShop()==1){
                boolean valid = true;//1.校验时间点内是否可预约；2.校验金额是否正确
                Double fee=0.0;
                valid = IsAppoint(roomId,startTime,endTime);
                Room entity = roomService.getById(roomId);
                if(valid){
                    long mins = 0;
                    mins = CalendarDate.dateDiff(startTime,endTime,"min");
                    Double min= Double.valueOf(mins);
                    Double cy=60.0;
                    fee= entity.getPrice()*(min/cy);
                    if(Double.doubleToLongBits(amount)!=Double.doubleToLongBits(fee)){
                        valid = false;
                    }
                }
                if(valid){
                    //计入流水
                    String orderNumner = paymentID()+"_xcx";
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    DateFormat dfdate = new SimpleDateFormat("yyyy-MM-dd");
                    String startHHmm=startTime.substring(11,16).replace(":","");
                    String endHHmm=endTime.substring(11,16).replace(":","");
                    Appointment data=new Appointment();
                    data.setStartTime(df.parse(startTime));
                    data.setEndTime(df.parse(endTime));
                    data.setCreateTime(new Date());
                    data.setPrice(entity.getPrice());
                    data.setRoomId(roomId);
                    data.setShopId(entity.getShopId());
                    data.setAppointDate(dfdate.parse(startTime));
                    data.setStartInt(Integer.valueOf(startHHmm));
                    data.setEndInt(Integer.valueOf(endHHmm));
                    data.setIsMessage(0);
                    data.setEvaluateScore(0);
                    data.setClientName(users.getUserName());
                    data.setClientPhone(users.getPhone());
                    data.setUserId(users.getUserID());
                    data.setIsMessageAdmin(0);
                    data.setStreamFlag(0);
                    data.setState(1);
                    data.setAmount(fee);
                    data.setTypes(2);
                    data.setWeChat(users.getOpenId());
                    data.setOrderNumber(orderNumner);
                    data.setPaymentTime(new Date());
                    b=appointmentService.save(data);
                }
            }
        }
        catch(Exception ex) {
            log.error(ex.getMessage());
        }
        return b;
    }
    /**
     *  用户余额预约
     * @param roomId 房间id
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @GetMapping("/amountAppoint")
    @ResponseBody
    public Boolean amountAppoint(@RequestParam(value = "roomId",required = false) Integer roomId,
                                  @RequestParam(value = "startTime",required = false) String startTime,
                                  @RequestParam(value = "endTime",required = false) String endTime,
                                  @RequestParam(value = "amount",required = false) String amount,
                                  @RequestParam(value = "userId",required = false) Integer userId,
                                  @RequestParam(value = "couponId",required = false) String couponId,
                                  @RequestParam(value = "sign",required = false) String sign) {
        Boolean b=false;Boolean c=false;
        log.info("-----------------------我是用户余额预约接口");
        try{
            String key="Z11f26";
            String str=roomId+startTime+endTime+amount+userId+couponId+key;
            log.info("-----------------------我是用户余额预约接口参数-roomId:"+roomId+"-startTime:"+startTime+"-endTime:"+endTime+
                    "-amount:"+amount+"-userId:"+userId+"-couponId:"+couponId+"-sign:"+sign);
            String md5sign=MD5.encrypt(str);
            log.info("-----------------------我是用户余额预约接口加密-md5sign:"+md5sign);
            if(md5sign.equals(sign)){
                log.info("-----------------------我是用户余额预约接口----验签成功");
                Double amount1=Double.valueOf(amount);
                Users users=userService.getById(userId);
                boolean valid = true;//1.校验时间点内是否可预约；2.校验金额是否正确
                Double fee=0.0;Double time=0.0;
                valid = IsAppoint(roomId,startTime,endTime);
                Room entity = roomService.getById(roomId);
                if(valid){
                    long mins = 0;
                    if(startTime.contains("00:00:00") && endTime.contains("24:00:00")){
                        mins=1440;
                    }else {
                        mins = CalendarDate.dateDiff(startTime,endTime,"min");
                    }
                    Double min= Double.valueOf(mins);
                    Double cy=60.0;
                    time=min/cy;
                    fee= entity.getPrice()*(min/cy);
                    if(Double.doubleToLongBits(amount1)!=Double.doubleToLongBits(fee)){
                        valid = false;
                    }
                }
                if(valid){
                    Double cstime=3.0;Double yktime=4.0;Double yktime2=24.0;
                    if(entity.getRoomType().equals("茶室") && time.equals(cstime)){
                        fee=108.0;
                        amount1=108.0;
                    }
                    if(entity.getRoomType().equals("影咖") && time.equals(yktime)){
                        fee=168.0;
                        amount1=168.0;
                    }
                    if(entity.getRoomType().equals("影咖") && time.equals(yktime2)){
                        fee=298.0;
                        amount1=298.0;
                    }
                    //优惠券抵扣金额
                    Double deduction=0.0;
                    if(!couponId.equals("null") && !couponId.equals("")){
                        deduction=couponAmount(Integer.valueOf(couponId),amount1);
                    }
                    //判断用户余额是否充足
                    Boolean enough=true;
                    amount1=amount1-deduction;
                    Double totalAmount=users.getFrozenAmount()+users.getAmount();
                    if(totalAmount.compareTo(amount1)>0){
                        if(users.getFrozenAmount().compareTo(amount1)>=0){
                            //扣除冻结金额
                            Double dealFrozenAmount=users.getFrozenAmount()-amount1;
                            users.setFrozenAmount(dealFrozenAmount);
                            userService.updateById(users);
                        }else if(users.getAmount().compareTo(amount1)>=0){
                            //扣除活动金额
                            Double dealAmount=users.getAmount()-amount1;
                            users.setAmount(dealAmount);
                            userService.updateById(users);
                        }else {
                            //先扣除冻结金额再扣除活动金额
                            Double dealFrozenAmount=amount1-users.getFrozenAmount();
                            Double dealAmount=users.getAmount()-dealFrozenAmount;
                            users.setFrozenAmount(0.0);
                            users.setAmount(dealAmount);
                            userService.updateById(users);
                        }
                        //计入流水
                        if(enough){
                            String orderNumner = paymentID()+"_xcx";
                            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            DateFormat dfdate = new SimpleDateFormat("yyyy-MM-dd");
                            String startHHmm=startTime.substring(11,16).replace(":","");
                            String endHHmm=endTime.substring(11,16).replace(":","");
                            Appointment data=new Appointment();
                            data.setStartTime(df.parse(startTime));
                            data.setEndTime(df.parse(endTime));
                            data.setCreateTime(new Date());
                            data.setPrice(entity.getPrice());
                            data.setRoomId(roomId);
                            data.setShopId(entity.getShopId());
                            data.setAppointDate(dfdate.parse(startTime));
                            data.setStartInt(Integer.valueOf(startHHmm));
                            data.setEndInt(Integer.valueOf(endHHmm));
                            data.setIsMessage(0);
                            data.setEvaluateScore(0);
                            data.setClientName(users.getUserName());
                            data.setClientPhone(users.getPhone());
                            data.setUserId(users.getUserID());
                            data.setIsMessageAdmin(0);
                            data.setStreamFlag(0);
                            data.setState(1);
                            data.setAmount(fee);
                            data.setTypes(2);
                            data.setWeChat(users.getOpenId());
                            data.setOrderNumber(orderNumner);
                            data.setPaymentTime(new Date());
                            b=appointmentService.save(data);
                            if(b  && !couponId.equals("null")){
                                Coupon coupon=couponService.getById(couponId);
                                coupon.setState(1);
                                b=couponService.updateById(coupon);
                            }
                        }
                    }
                }
            }
        }catch(Exception ex) {
            log.error(ex.getMessage());
        }
        return b;
    }
    /**
     *  用户余额续费
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @GetMapping("/amountRenewal")
    @ResponseBody
    public Boolean amountRenewal(@RequestParam(value = "startTime",required = false) String startTime,
                                 @RequestParam(value = "endTime",required = false) String endTime,
                                 @RequestParam(value = "amount",required = false) String amount,
                                 @RequestParam(value = "attributionOrder",required = false) String attributionOrder,
                                 @RequestParam(value = "couponId",required = false) String couponId,
                                 @RequestParam(value = "sign",required = false) String sign) {
        Boolean b=false;Boolean c=false;
        try {
            String key="Z11f26";
            String str=startTime+endTime+amount+attributionOrder+couponId+key;
            String md5sign=MD5.encrypt(str);
            if(md5sign.equals(sign)){
                Double amount1=Double.valueOf(amount);
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //查出对应的订单
                QueryWrapper<Appointment> appwrapper =new QueryWrapper<Appointment>();
                appwrapper.eq("orderNumber",attributionOrder);
                Appointment applist= appointmentService.getBaseMapper().selectOne(appwrapper);
                Integer roomId = applist.getRoomId();
                Users users = userService.getById(applist.getUserId());
                Room entity = roomService.getById(roomId);
                boolean valid = false;//1.校验时间点内是否可续费；2.校验金额是否正确
                String appEndTime=df.format(applist.getEndTime());
                if(appEndTime.equals(startTime)){
                    valid = isRenewal(roomId,startTime,endTime);
                }
                if(valid){
                    long mins = 0;
                    mins = CalendarDate.dateDiff(startTime,endTime,"min");
                    Double min= Double.valueOf(mins);
                    Double cy=60.0;Double fee=0.0;
                    fee= entity.getPrice()*(min/cy);
                    if(Double.doubleToLongBits(amount1)!=Double.doubleToLongBits(fee)){
                        valid=false;
                    }
                }
                if(valid){
                    //优惠券抵扣金额
                    Double deduction=0.0;
                    if(!couponId.equals("null") && !couponId.equals("")){
                        deduction=couponAmount(Integer.valueOf(couponId),amount1);
                    }
                    //判断用户余额是否充足
                    Boolean enough=true;
                    amount1=amount1-deduction;
                    Double totalAmount=users.getFrozenAmount()+users.getAmount();
                    if(totalAmount.compareTo(amount1)>0){
                        if(users.getFrozenAmount().compareTo(amount1)>=0){
                            //扣除冻结金额
                            Double dealFrozenAmount=users.getFrozenAmount()-amount1;
                            users.setFrozenAmount(dealFrozenAmount);
                            userService.updateById(users);
                        }else if(users.getAmount().compareTo(amount1)>=0){
                            //扣除活动金额
                            Double dealAmount=users.getAmount()-amount1;
                            users.setAmount(dealAmount);
                            userService.updateById(users);
                        }else {
                            //先扣除冻结金额再扣除活动金额
                            Double dealFrozenAmount=amount1-users.getFrozenAmount();
                            Double dealAmount=users.getAmount()-dealFrozenAmount;
                            users.setFrozenAmount(0.0);
                            users.setAmount(dealAmount);
                            userService.updateById(users);
                        }
                        //计入流水
                        if(enough){
                            String orderNumner = paymentID()+"_xcx";
                            DateFormat dfdate = new SimpleDateFormat("yyyy-MM-dd");
                            String startHHmm=startTime.substring(11,16).replace(":","");
                            String endHHmm=endTime.substring(11,16).replace(":","");
                            Appointment data=new Appointment();
                            data.setStartTime(df.parse(startTime));
                            data.setEndTime(df.parse(endTime));
                            data.setCreateTime(new Date());
                            data.setPrice(entity.getPrice());
                            data.setRoomId(roomId);
                            data.setParentAppId(applist.getId());
                            data.setShopId(entity.getShopId());
                            data.setAppointDate(dfdate.parse(startTime));
                            data.setStartInt(Integer.valueOf(startHHmm));
                            data.setEndInt(Integer.valueOf(endHHmm));
                            data.setIsMessage(0);
                            data.setEvaluateScore(0);
                            data.setClientName(users.getUserName());
                            data.setClientPhone(users.getPhone());
                            data.setUserId(users.getUserID());
                            data.setIsMessageAdmin(0);
                            data.setStreamFlag(0);
                            data.setState(1);
                            data.setAmount(amount1);
                            data.setTypes(2);
                            data.setWeChat(users.getOpenId());
                            data.setOrderNumber(orderNumner);
                            data.setPaymentTime(new Date());
                            b=appointmentService.save(data);
                            //延长房间供电
                            Date start=data.getStartTime();
                            Date end=data.getEndTime();
                            Long diff=(end.getTime()-start.getTime())/60/1000;
                            Integer minute=diff.intValue();
                            QueryWrapper<Middlecommand> middWrapper =new QueryWrapper<Middlecommand>();
                            middWrapper.eq("status",0);
                            middWrapper.eq("roomId",data.getRoomId());
                            middWrapper.gt("actionTime",new Date());
                            List<Middlecommand> middList = middlecommandService.getBaseMapper().selectList(middWrapper);
                            for(Middlecommand midd:middList){
                                Date actionTime=midd.getActionTime();
                                Calendar calendars = Calendar.getInstance();
                                calendars.setTime(actionTime);
                                calendars.add(Calendar.MINUTE, +minute);
                                midd.setActionTime(calendars.getTime());
                                middlecommandService.updateById(midd);
                            }
                            if(b && !couponId.equals("null")){
                                Coupon coupon=couponService.getById(couponId);
                                coupon.setState(1);
                                b=couponService.updateById(coupon);
                            }
                        }
                    }
                }
            }
        }catch(Exception ex) {
            log.error(ex.getMessage());
        }
        return b;
    }
    /**
     *  用户余额待支付订单
     * @return
     */
    @GetMapping("/amountDefray")
    @ResponseBody
    public Boolean amountDefray( @RequestParam(value = "attributionOrder",required = false) String attributionOrder,
                                 @RequestParam(value = "couponId",required = false) String couponId,
                                 @RequestParam(value = "sign",required = false) String sign) {
        Boolean b=false;Boolean c=false;
        try {
            String key="Z11f26";
            String str=attributionOrder+couponId+key;
            String md5sign=MD5.encrypt(str);
            if(md5sign.equals(sign)){
                //查出对应的订单
                QueryWrapper<Appointment> appwrapper =new QueryWrapper<Appointment>();
                appwrapper.eq("orderNumber",attributionOrder);
                Appointment applist= appointmentService.getBaseMapper().selectOne(appwrapper);
                if(applist!=null){
                    //优惠券抵扣金额
                    Double deduction=0.0;Double amount=applist.getAmount();
                    if(!couponId.equals("null") && !couponId.equals("")){
                        deduction=couponAmount(Integer.valueOf(couponId),amount);
                    }
                    //判断用户余额是否充足
                    Boolean enough=true;
                    amount=amount-deduction;
                    Users users = userService.getById(applist.getUserId());
                    Double totalAmount=users.getFrozenAmount()+users.getAmount();
                    if(totalAmount.compareTo(amount)>0){
                        if(users.getFrozenAmount().compareTo(amount)>=0){
                            //扣除冻结金额
                            Double dealFrozenAmount=users.getFrozenAmount()-amount;
                            users.setFrozenAmount(dealFrozenAmount);
                            userService.updateById(users);
                        }else if(users.getAmount().compareTo(amount)>=0){
                            //扣除活动金额
                            Double dealAmount=users.getAmount()-amount;
                            users.setAmount(dealAmount);
                            userService.updateById(users);
                        }else {
                            //先扣除冻结金额再扣除活动金额
                            Double dealFrozenAmount=amount-users.getFrozenAmount();
                            Double dealAmount=users.getAmount()-dealFrozenAmount;
                            users.setFrozenAmount(0.0);
                            users.setAmount(dealAmount);
                            userService.updateById(users);
                        }
                        //计入流水
                        if(enough){
                            applist.setState(1);
                            applist.setPaymentTime(new Date());
                            b=appointmentService.updateById(applist);
                            if(b && !couponId.equals("null")){
                                Coupon coupon=couponService.getById(couponId);
                                coupon.setState(1);
                                b=couponService.updateById(coupon);
                            }
                        }
                    }
                }
            }
        }catch(Exception ex) {
            log.error(ex.getMessage());
        }
        return b;
    }
    /**
     *  开售货柜格子(自研）
     * @param  cabinetitemId 格子id
     * @return
     */
    @GetMapping("/cabinetitem")
    @ResponseBody
    public String cabinetitem(@RequestParam(value = "cabinetitemId",required = false) Integer cabinetitemId,
                            @RequestParam(value = "allopen",required = false) Integer allopen) {
        String reulst = "Error";Boolean b=false;
        Cabinetitem cabinetitem=cabinetitemService.getById(cabinetitemId);
        Cabinet cabinet=cabinetService.getById(cabinetitem.getCabId());
        String timestamp = String.valueOf(new Date().getTime()/1000);
        String cabCommand="";
        if(allopen!=null && !allopen.equals("")){
            cabCommand="3;"+cabinet.getCommand()+";"+timestamp+";"+allopen+";0;#";
            if(allopen==999){
                b=true;
            }
        }else {
            cabCommand="3;"+cabinet.getCommand()+";"+timestamp+";"+cabinetitem.getNum()+";0;#";
        }
        System.out.println(cabCommand);
        String sendCommand = convertStringToHex(cabCommand);
        System.out.println(sendCommand);
        reulst=actionService.SendAction(cabinet.getTopic(),sendCommand,new Date(),1,"售货柜开格子",0,cabinetitem.getCabId(),0,cabinet.getRoomId(),cabinet.getShopId());
        if(b){
            String cabCommand1="3;"+cabinet.getCommand()+";"+timestamp+";21;0;#";
            String sendCommand1 = convertStringToHex(cabCommand1);
            actionService.SendAction(cabinet.getTopic(),sendCommand1,new Date(),1,"售货柜开格子",0,cabinetitem.getCabId(),0,cabinet.getRoomId(),cabinet.getShopId());

            String cabCommand2="3;"+cabinet.getCommand()+";"+timestamp+";22;0;#";
            String sendCommand2 = convertStringToHex(cabCommand2);
            actionService.SendAction(cabinet.getTopic(),sendCommand2,new Date(),1,"售货柜开格子",0,cabinetitem.getCabId(),0,cabinet.getRoomId(),cabinet.getShopId());

            String cabCommand3="3;"+cabinet.getCommand()+";"+timestamp+";23;0;#";
            String sendCommand3 = convertStringToHex(cabCommand3);
            actionService.SendAction(cabinet.getTopic(),sendCommand3,new Date(),1,"售货柜开格子",0,cabinetitem.getCabId(),0,cabinet.getRoomId(),cabinet.getShopId());

            String cabCommand4="3;"+cabinet.getCommand()+";"+timestamp+";24;0;#";
            String sendCommand4 = convertStringToHex(cabCommand4);
            actionService.SendAction(cabinet.getTopic(),sendCommand4,new Date(),1,"售货柜开格子",0,cabinetitem.getCabId(),0,cabinet.getRoomId(),cabinet.getShopId());
        }
        return reulst;
    }
    /**
     *  开售货柜格子(大马）
     * @param  cabinetitemId 格子id
     * @return
     */
    @GetMapping("/cabinetitemdm")
    @ResponseBody
    public String cabinetitemdm(@RequestParam(value = "cabinetitemId",required = false) Integer cabinetitemId,
                              @RequestParam(value = "allopen",required = false) Integer allopen) {
        String reulst = "Error";
        Cabinetitem cabinetitem=cabinetitemService.getById(cabinetitemId);
        Cabinet cabinet=cabinetService.getById(cabinetitem.getCabId());
        String channellist="";
        if(allopen!=null){
            if(allopen.equals(999)){
                QueryWrapper<Cabinetitem> wrapper=new QueryWrapper<Cabinetitem>();
                wrapper.eq("cabId",cabinetitem.getCabId());
                List<Cabinetitem> datalist=cabinetitemService.list(wrapper);
                for(Cabinetitem cab:datalist){
                    channellist=channellist+cab.getNum()+",";
                }
                channellist=channellist.substring(0,channellist.length()-1);
            }
        }
        if(allopen!=null && !allopen.equals("")){
            reulst=actionService.SendActiondm(cabinet.getDevCode(),cabinet.getKeyId(),new Date(),1,"售货柜开格子",0,cabinetitem.getCabId(),allopen,cabinet.getRoomId(),cabinet.getShopId(),channellist);
        }else {
            reulst=actionService.SendActiondm(cabinet.getDevCode(),cabinet.getKeyId(),new Date(),1,"售货柜开格子",0,cabinetitem.getCabId(),Integer.valueOf(cabinetitem.getNum()),cabinet.getRoomId(),cabinet.getShopId(),channellist);
        }
        return reulst;
    }
    public String convertStringToHex(String str){
        char[] chars = str.toCharArray();
        StringBuffer hex = new StringBuffer();
        for(int i = 0; i < chars.length; i++){
            hex.append(Integer.toHexString((int)chars[i]));
        }
        return hex.toString();
    }
    /**
     * 用户的优惠券
     * @param userId 用户id
     * @return
     */
    @GetMapping("/isCoupon")
    @ResponseBody
    public List<Coupon> isCoupon(@RequestParam(value = "userId",required = false) Integer userId){
        Date today=new Date();
        QueryWrapper<Coupon> wrapper =new QueryWrapper<Coupon>();
        wrapper.eq("userId",userId);
        List<Coupon> coupons=couponService.list(wrapper);
        for(Coupon coupon:coupons){
            if(coupon.getStartTime().compareTo(today)>0 || coupon.getEndTime().compareTo(today)<0){
                coupon.setState(-1);
            }
        }
        return coupons;
    }
    /**
     * 返回优惠券抵扣金额
     * @param id 优惠券id
     * @param amount 订单金额
     * @return
     */
    public Double couponAmount(Integer id,Double amount){
        Coupon coupon=couponService.getById(id);
        Date today=new Date();
        Double deduction=0.0;
        if(coupon.getStartTime().compareTo(today)<0 && coupon.getEndTime().compareTo(today)>0
                && coupon.getState()==0 && amount.compareTo(coupon.getAmount())>=0){
            deduction=coupon.getMoney();
        }
        return deduction;
    }
    /**
     * 用户的余额
     * @param userId 用户id
     * @return
     */
    @GetMapping("/userAmount")
    @ResponseBody
    public Double userAmount(@RequestParam(value = "userId",required = false) Integer userId){
        Double userAmount=0.0;
        Users users=userService.getById(userId);
        if(users!=null){
            if(users.getAmount()!=null && !users.getAmount().equals("")){
                userAmount=userAmount+users.getAmount();
            }
            if(users.getFrozenAmount()!=null && !users.getFrozenAmount().equals("")){
                userAmount=userAmount+users.getFrozenAmount();
            }
        }
        return userAmount;
    }
    /**
     *  判断是否是会员
     * @param userId 用户id
     * @return
     */
    @GetMapping("/isMember")
    @ResponseBody
    public boolean isMember(@RequestParam(value = "userId",required = false) Integer userId){
        Boolean b=false;
        Users users=userService.getById(userId);
        if(users.getUserType()==5){
            b=true;
        }
        return b;
    }
    /**
     *  判断是否是合伙人
     * @param userId 用户id
     * @return
     */
    @GetMapping("/isPartner")
    @ResponseBody
    public boolean isPartner(@RequestParam(value = "userId",required = false) Integer userId){
        Boolean b=false;
        Users users=userService.getById(userId);
        if(users.getUserType()==2){
            b=true;
        }
        return b;
    }
    /**
     *  测试
     * @return
     */
    @GetMapping("/test")
    @ResponseBody
    public boolean test(@RequestParam(value = "orderNumberMain",required = false) String orderNumberMain){
        Boolean b=false;
        QueryWrapper<Registorder> wrapper =new QueryWrapper<Registorder>();
        wrapper.eq("orderNumber",orderNumberMain);
        Registorder data=registorderService.getBaseMapper().selectOne(wrapper);
        data.setState(1);
        registorderService.updateById(data);
        //查询活动
        QueryWrapper<Event> queryWrapper =new QueryWrapper<Event>();
        queryWrapper.eq("eventId",1);
        Event event=eventService.getOne(queryWrapper);
        //认证会员
        Users users=userService.getById(data.getUserId());
        users.setTypes(1);
        users.setUserType(5);
        Double amount=users.getFrozenAmount()+event.getAmount();
        Double shopAmount=users.getShopAmount()+event.getAmount();
        users.setFrozenAmount(amount);
        users.setShopAmount(shopAmount);
        userService.updateById(users);
        //修改角色权限表
        QueryWrapper<UserRoles> rolesQueryWrapper =new QueryWrapper<UserRoles>();
        rolesQueryWrapper.eq("userID",data.getUserId());
        UserRoles userRoles=new UserRoles();
        userRoles.setUserID(data.getUserId());
        userRoles.setRoleID(5);
        userRolesService.update(userRoles,rolesQueryWrapper);
        return b;
    }
    /**
     * 会员权益
     * @return
     */
    @GetMapping("/memberRights")
    @ResponseBody
    public JSONObject memberRights(){
        QueryWrapper<EventplannVo> wrapper =new QueryWrapper<EventplannVo>();
        wrapper.eq("A.id",1);
        List<EventplannVo> eventplannVos=eventplannService.search(wrapper,new Page<>(1,9999));
        JSONObject object=new JSONObject();
        if(eventplannVos.size()>0){
            object.put("amount",eventplannVos.get(0).getEventAmount().intValue());
            String str="<strong>"+eventplannVos.get(0).getEventRemark()+"</strong>";
            object.put("rights",str);
        }
        return object;
    }
    /**
     * 合伙人权益
     * @return
     */
    @GetMapping("/partnerRights")
    @ResponseBody
    public JSONObject partnerRights(@RequestParam(value = "userId",required = false) Integer userId){
        QueryWrapper<EventplannVo> wrapper =new QueryWrapper<EventplannVo>();
        wrapper.eq("A.id",2);
        List<EventplannVo> eventplannVos=eventplannService.search(wrapper,new Page<>(1,9999));
        JSONObject object=new JSONObject();
        if(eventplannVos.size()>0){
            object.put("amount",eventplannVos.get(0).getEventAmount().intValue());
            String str="<strong>"+eventplannVos.get(0).getEventRemark()+"</strong>";
            object.put("rights",str);
        }
        return object;
    }


}
